package com.cjt.chat.service.impl;

import com.cjt.chat.mapper.GroupMapper;
import com.cjt.chat.mapper.MessageMapper;
import com.cjt.chat.pojo.Message;
import com.cjt.chat.pojo.User;
import com.cjt.chat.service.MessageService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author cjt
 * @since 2024/3/27
 */
@Service
public class MessageServiceImpl implements MessageService {
    @Resource
    private MessageMapper messageMapper;
    @Resource
    private GroupMapper groupMapper;

    @Override
    public List<Message> getMessageHistory(Integer friendId, Integer userId, Integer page) {
        System.out.println(page);
        return messageMapper.getMessageHistory(friendId, userId, page * 30);
    }

    @Override
    public void saveMessage(Message message) {
        messageMapper.saveMessageOne(message);
    }

    @Override
    public Map<String, Message> getNewMessage(List<User> friendList, Integer userId) {
        Map<String, Message> newMessageMap = new HashMap<>();
        for (User friend : friendList) {
            Message newMessage = messageMapper.getNewMessage(userId, friend.getUserid());
            newMessageMap.put(friend.getUserid().toString(), newMessage);
        }
        return newMessageMap;
    }

    @Override
    public List<Message> getSystemMessage(Integer userId) {
        List<Message> friendRequest = messageMapper.getFriendRequest(userId);
        List<Integer> groupIds = groupMapper.queryAllGroupByMasterId(userId);
        if (groupIds != null && !groupIds.isEmpty()) {
            List<Message> joinGroupRequest = messageMapper.getJoinGroupRequest(groupIds);
            friendRequest.addAll(joinGroupRequest);
        }
        return friendRequest;
    }

    @Override
    public void deleteMessageById(Integer messageId) {
        messageMapper.deleteMessageByMessageId(messageId);
    }

    @Override
    public List<Message> getAllMessageHistory(Integer friendId, Integer userId) {
        return messageMapper.queryAllMessageHistory(friendId, userId);
    }
}
